package com.lg.startertemplate.utiles;

import com.lg.startertemplate.exception.CommonException;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class CommandUtils {
    //执行系统命令
    public static String executeLinuxCmd(String cmd) {
        log.info("执行命令[ " + cmd + " ]");
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(cmd);
            String line;
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer out = new StringBuffer();
            while ((line = stdoutReader.readLine()) != null ) {
                out.append(line);
                log.info(line);
            }
            try {
               log.info("返回值: " + process.waitFor());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            process.destroy();
           log.info("out.toString(): " + out.toString());
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置环境变量 并执行 系统命令
     *
     *      测试执行linux 命令
     *      java -jar placeservice-6.1.0-snapshot.jar "pg_dump -h 192.168.120.85 -p 5431 -U postgres -d place0922_base -F d -f ./test6" "PGPASSWORD=postgres"
     *      String[] envp = {args[1]};
     */
    public static Integer executeLinuxCmd(String cmd,String[] envp) {
       log.info("执行命令[ " + cmd + " ]");
        Runtime run = Runtime.getRuntime();
        int res = 0;
        try {
            Process process = run.exec(cmd,envp);
            String line;
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer out = new StringBuffer();
            while ((line = stdoutReader.readLine()) != null ) {
                out.append(line);
                log.info(line);
            }
            try {
                res = process.waitFor();
            } catch (InterruptedException e) {
                log.error("执行命令[ " + cmd + " ] "+"出错",e);
                throw new CommonException("执行系统出错");
            }
            process.destroy();
            if (res == 0)
                log.info("系统命令执行成功");
            else
                log.info("系统命令执行失败");

            return res;
        } catch (IOException e) {
            log.error("执行命令[ " + cmd + " ] "+"出错",e);
            throw new CommonException("执行系统出错");
        }
    }

}
